/**
 * 
 */
package com.zufangbao.earth.handler.impl;

import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.demo2do.core.utils.JsonUtils;
import com.zufangbao.earth.handler.OpenApiHandler;

/**
 * @author wukai
 *
 */
@Component("openApiHandler")
public class OpenApiHandlerImpl implements OpenApiHandler {
	
	public static Log logger = LogFactory.getLog(OpenApiHandlerImpl.class);
	
	@Value("#{config['timeout']}")
	public int TIMEOUT;

	@Override
	public String createShortUrl(String longUrl) {
		
		String openGenerateShortUrl = "https://api.weibo.com/2/short_url/shorten.json";
		
		String appKey = "403017092";
		
		try {
			
			logger.info("begin to create short url with long url["+longUrl+"]");
		
			Response response = Jsoup.connect(openGenerateShortUrl)
									 .ignoreContentType(true)
									 .method(Method.GET)
									 .data("source",appKey)
									 .data("url_long",longUrl)
									 .timeout(TIMEOUT)
									 .execute();
			
			logger.info("get the reponse["+ response.body() + "]");
			
			Map<String,Object> resultMap = JsonUtils.parse(response.body(),Map.class);
			
			if(null == resultMap){
				
				return null;
			}
			List<Map<String,Object>> mapList = JsonUtils.parseArray(resultMap.get("urls").toString());
			
			if(CollectionUtils.isEmpty(mapList)){
				
				return null;
			}
			
			Map<String,Object> map = mapList.get(0);
			
			boolean isValidShortUrl = StringUtils.equals(map.get("result").toString(),"true");
			
			if(isValidShortUrl){
				
				return map.get("url_short").toString();
			}
			
			return null;
			
		} catch (Exception e) {
			
			logger.error("get short url error : " + e.getMessage());
			
		}
		return null;
	}

}
